package com.leruan.aasimp.action.forum;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.leruan.aasimp.constant.UsedCarConstant;
import com.leruan.aasimp.entity.Board;
import com.leruan.aasimp.entity.Forumstst;
import com.leruan.aasimp.entity.Forumuser;
import com.leruan.aasimp.entity.Mainpost;
import com.leruan.aasimp.entity.Sensitive;
import com.leruan.aasimp.entitydto.BrandMap;
import com.leruan.aasimp.entitydto.MainPostDto;
import com.leruan.aasimp.entitydto.StaticStrings;
import com.leruan.aasimp.service.AdminService;
import com.leruan.aasimp.service.BoardService;
import com.leruan.aasimp.service.ForumUserService;
import com.leruan.aasimp.service.MainPostService;
import com.leruan.aasimp.service.ReplyService;
import com.leruan.aasimp.util.ArticleUtils;
import com.leruan.aasimp.util.DateUtils;
import com.leruan.aasimp.util.StringUtil;
import com.leruan.aasimp.util.Validators;
import com.opensymphony.xwork2.ActionSupport;

public class PostAction extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 8037891103236983630L;
    @Resource
    private BoardService boardService;
    @Resource
    private MainPostService mainPostService;
    @Resource
    private ReplyService replyService;
    @Resource
    private ForumUserService forumUserService;
    @Resource
    private AdminService adminService;

    private List<Board> boards = new ArrayList<Board>();
    private String boardId;
    private String userId;
    private String postTitle;
    private String content;
    private String postId;
    private Date postDate;
    private Date modifyDate;
    private String fileName = "";
    private Map<String, String> brandMap;
    public StringBuffer brands = new StringBuffer();
    private Board board;
    private List<MainPostDto> mainPosts = new ArrayList<MainPostDto>();// 帖子列表
    public List<MainPostDto> topMainPosts = new ArrayList<MainPostDto>();// 置顶帖子列表
    private Forumuser forumuser;
    public Map<String, String> forumuserNameMap = new HashMap<String, String>();
    private Forumuser lastuser;
    public Map<String, String> lastPostUserMap = new HashMap<String, String>();
    public Map<String, Date> lastPostTimeMap = new HashMap<String, Date>();

    // 板块帖子列表
    public String boardPostList() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        boardId = request.getParameter("boardId");
        // topTopic();
        if (!Validators.isEmpty(boardId)) {
            board = boardService.getBoardById(boardId);
            board.setHits(board.getHits() + 1);
            boardService.modifyBoardHits(board);
        }
        int pageNo = 1;
        try {
            // mainPosts = mainPostService.getMainPostsByBoardId(boardId);
            mainPosts = mainPostService.getMainPostsByBoardId(boardId, null, pageNo);
            for (Mainpost mp : mainPosts) {
                forumuser = forumUserService.getBoardUserById(mp.getUserId());
                forumuserNameMap.put(forumuser.getUserId(), forumuser.getUsername());
                lastuser = forumUserService.getBoardUserById(mp.getLastReplyUserId());
                if (null == lastuser || null == mp.getLastReplyDate()) {
                    continue;
                }
                lastPostUserMap.put(mp.getPostId(), lastuser.getUsername());
                lastPostTimeMap.put(mp.getPostId(), mp.getLastReplyDate());
            }

            Long total = mainPostService.getMainPostTotal(boardId, null);
            request.setAttribute("board", board);
            request.setAttribute("boardId", boardId);
            request.setAttribute("mainPosts", mainPosts);
            request.setAttribute("forumuserNameMap", forumuserNameMap);
            request.setAttribute("lastPostUserMap", lastPostUserMap);
            request.setAttribute("lastPostTimeMap", lastPostTimeMap);
            session.setAttribute("pageNoSale", pageNo);
            session.setAttribute("pageNoCenterSale", 3);
            session.setAttribute("totalNoSale", total / UsedCarConstant.PAGE_SIZE + 1);
            session.setAttribute("totalSale", total);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    private void topTopic() {
        HttpServletRequest request = ServletActionContext.getRequest();
        topMainPosts = mainPostService.getMainPostsByBoardId(boardId, null, 0);

        request.setAttribute("topMainPosts", topMainPosts);
    }

    public String boardPostListQuery() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        boardId = request.getParameter("boardId");
         topTopic();
        Map<String, String> map = new HashMap<String, String>();
        int pageNo = Integer.parseInt(request.getParameter("no"));

        try {
            mainPosts = mainPostService.getMainPostsByBoardId(boardId, null, pageNo);
            for (Mainpost mp : mainPosts) {
                forumuser = forumUserService.getBoardUserById(mp.getUserId());
                forumuserNameMap.put(forumuser.getUserId(), forumuser.getUsername());
                lastuser = forumUserService.getBoardUserById(mp.getLastReplyUserId());
                if (null == lastuser || null == mp.getLastReplyDate()) {
                    continue;
                }
                lastPostUserMap.put(mp.getPostId(), lastuser.getUsername());
                lastPostTimeMap.put(mp.getPostId(), mp.getLastReplyDate());
            }
            board = boardService.getBoardById(boardId);
            request.setAttribute("board", board);
            request.setAttribute("boardId", boardId);
            request.setAttribute("mainPosts", mainPosts);
            request.setAttribute("forumuserNameMap", forumuserNameMap);
            request.setAttribute("lastPostUserMap", lastPostUserMap);
            request.setAttribute("lastPostTimeMap", lastPostTimeMap);
            session.setAttribute("pageNoSale", pageNo);
            Long total = (Long) session.getAttribute("totalNoSale");
            if (pageNo < 3 || total < 5) {
                session.setAttribute("pageNoCenterSale", 3);
            }
            else if (pageNo > total - 2) {
                session.setAttribute("pageNoCenterSale", total - 2);
            }
            else {
                session.setAttribute("pageNoCenterSale", pageNo);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    public String newPost() {
        HttpServletRequest request = ServletActionContext.getRequest();
        String boardId = request.getParameter("boardId");
        if (!Validators.isEmpty(boardId)) {
            Board selectedBoard = new Board();
            Board board = boardService.getBoardById(boardId);
            selectedBoard = boardService.getBoardById(boardId);
            request.setAttribute("board", board);
            request.setAttribute("selectedBoard", selectedBoard);
            if (Validators.isEmpty(selectedBoard.getBoardName())) {
                addActionError("板块不存在");
                return "success";
            }
        }
        boards = boardService.getBoard();
        request.setAttribute("boards", boards);
        return "success";
    }

    public String addNewPost() throws UnsupportedEncodingException {
        HttpServletRequest request = ServletActionContext.getRequest();
        postId = StringUtil.getUUID();
        postTitle = request.getParameter("postTitle");
        userId = request.getParameter("userId");
        content = request.getParameter("content");
        postDate = new Date();
        boardId = request.getParameter("boardId");
        Mainpost mainpost = new Mainpost(postId, postTitle, userId, 3l, content, postDate, 0l, 0l, boardId, null, null,
                postDate, 0l, 0l);
        validatePost(mainpost);
        List<String> judgeTabooedWords = ArticleUtils.judgeTabooedWords(postTitle + content);
        // List<String> judgeTabooedWords = new ArrayList<String>();
        // judgeTabooedWords = TabooedUtils.getTabooedWords((postTitle + content).toString());
        if (Validators.isEmpty(judgeTabooedWords)) {
            if (!Validators.isEmpty(mainpost.getContent())) {
                String filePath = StaticStrings.FILEPATH;
                String absolutePath = "";// 文件存放路径
                String absoluteRootPath = filePath + "/" + "post/content" + "/";// 获取存放目标文件的根目录
                String curDate = DateUtils.date2String(new Date(), "yyyyMMdd");
                absolutePath = absoluteRootPath + curDate;

                // 若目录不存在，则创建,以uuid做为文件名存放
                File d = new File(absolutePath);
                if (!d.exists()) {
                    d.mkdirs();
                }

                String uuid = StringUtil.getUUID();
                fileName = uuid + "." + "txt";
                String fileURL = curDate + "/" + fileName;
                fileName = absolutePath + "/" + fileName;
                if (!ArticleUtils.saveArticleTxtFile(mainpost.getContent(), fileName)) {
                    addActionError("帖子内容发布失败");
                    request.setAttribute("boardId", boardId);
                    return "wrong";
                }
                fileName = "post/content" + "/" + fileURL;
            }
            mainpost.setContent(fileName);
            mainPostService.addMainPost(mainpost);
            // 修改板块帖数
            Board board = boardService.getBoardById(boardId);
            board.setPostNum(board.getPostNum() + 1);
            boardService.modifyBoardHits(board);

            // 增加论坛统计
            List<String> judgeBrandWords = ArticleUtils.judgeBrandWords(postTitle + content);
            // List<String> judgeBrandWords = new ArrayList<String>();
            // judgeBrandWords = TabooedUtils.getTabooedWords((postTitle + content).toString());
            brandMap = BrandMap.getBrandMap();
            for (String name : judgeBrandWords) {
                brands.append(brandMap.get(name));
            }
            Forumstst forumstst = mainPostService.getForumststByUserId(mainpost.getUserId());
            if (null == forumstst) {
                forumstst = new Forumstst(mainpost.getUserId(), brands.toString(), new Date(), new Date());
                mainPostService.addForumstst(forumstst);
            }
            else {
                forumstst.setBrands(forumstst.getBrands() + brands.toString());
                forumstst.setModifyTime(new Date());
                mainPostService.modifyForumstst(forumstst);
            }

            addActionError("帖子发布成功");
            request.setAttribute("boardId", boardId);
            return "success";
        }
        else {
            StringBuffer sb = new StringBuffer();
            for (String s : judgeTabooedWords) {
                sb.append(s);
                sb.append(",");
            }
            addActionError("您发布的帖子中有敏感词汇，如下" + sb + "请删除这些敏感词后再发布");
            addActionMessage("您发布的帖子中有敏感词汇，如下" + sb + "请删除这些敏感词后再发布");
            String sensitiveId = StringUtil.getUUID();
            Sensitive sensitive = new Sensitive(userId, sb.toString(), new Date(), sensitiveId, boardId);
            adminService.addSensitive(sensitive);
            request.setAttribute("boardId", boardId);
            return "wrong";
        }
    }

    public String showEditPost() {
        HttpServletRequest request = ServletActionContext.getRequest();
        postId = request.getParameter("postId");
        boardId = request.getParameter("boardId");
        Mainpost mainpost = mainPostService.getMainPostsByPostId(postId);
        boards = boardService.getBoard();
        board = boardService.getBoardById(boardId);
        if (!Validators.isEmpty(mainpost.getContent())) {
            String filePath = StaticStrings.FILEPATH;
            filePath = filePath + mainpost.getContent();
            mainpost.setContent(ArticleUtils.readArticleFromFile(filePath));
        }

        request.setAttribute("boards", boards);
        request.setAttribute("board", board);
        request.setAttribute("mainpost", mainpost);
        return "success";
    }

    public String editPost() {
        HttpServletRequest request = ServletActionContext.getRequest();
        postId = request.getParameter("postId");
        Mainpost mainpost = mainPostService.getMainPostsByPostId(postId);

        boardId = request.getParameter("boardId");
        postTitle = request.getParameter("postTitle");
        content = request.getParameter("content");
        modifyDate = new Date();
        mainpost.setBoardId(boardId);
        mainpost.setPostTitle(postTitle);
        mainpost.setModifyDate(modifyDate);
        StaticStrings.setTABOOEDORNOT(true);
        List<String> judgeTabooedWords = ArticleUtils.judgeTabooedWords(postTitle + content);
        // List<String> judgeTabooedWords = new ArrayList<String>();
        // judgeTabooedWords = TabooedUtils.getTabooedWords((postTitle + content).toString());
        if (Validators.isEmpty(judgeTabooedWords)) {
            if (!Validators.isEmpty(mainpost.getContent())) {
                String filePath = StaticStrings.FILEPATH;
                String absolutePath = "";// 文件存放路径
                String absoluteRootPath = filePath + "/" + "post/content" + "/";// 获取存放目标文件的根目录
                String curDate = DateUtils.date2String(new Date(), "yyyyMMdd");
                absolutePath = absoluteRootPath + curDate;

                // 若目录不存在，则创建,以uuid做为文件名存放
                File d = new File(absolutePath);
                if (!d.exists()) {
                    d.mkdirs();
                }

                String uuid = StringUtil.getUUID();
                fileName = uuid + "." + "txt";
                String fileURL = curDate + "/" + fileName;
                fileName = absolutePath + "/" + fileName;
                if (!ArticleUtils.saveArticleTxtFile(content, fileName)) {
                    addActionError("帖子内容修改失败");
                    return "wrong";
                }
                fileName = "post/content" + "/" + fileURL;
            }
            mainpost.setContent(fileName);
            mainPostService.modifyMainPost(mainpost);
            addActionError("帖子内容修改成功");
            // 修改论坛统计表
            StaticStrings.setTABOOEDORNOT(false);
            List<String> judgeBrandWords = ArticleUtils.judgeBrandWords(postTitle + content);
            // List<String> judgeBrandWords = new ArrayList<String>();
            // judgeTabooedWords = TabooedUtils.getTabooedWords((postTitle + content).toString());
            brandMap = BrandMap.getBrandMap();
            for (String name : judgeBrandWords) {
                brands.append(brandMap.get(name));
            }
            Forumstst forumstst = mainPostService.getForumststByUserId(mainpost.getUserId());
            if (null == forumstst) {
                forumstst = new Forumstst(mainpost.getUserId(), boards.toString(), new Date(), new Date());
                mainPostService.addForumstst(forumstst);
            }
            else {
                forumstst.setBrands(forumstst.getBrands() + brands.toString());
                forumstst.setModifyTime(new Date());
                mainPostService.modifyForumstst(forumstst);
            }
            Board board = boardService.getBoardById(boardId);
            request.setAttribute("boardId", boardId);
            return "success";
        }
        else {
            StringBuffer sb = new StringBuffer();
            for (String s : judgeTabooedWords) {
                sb.append(s);
                sb.append(",");
            }
            addActionError("您发布的帖子中有敏感词汇，如下" + sb + "请删除这些敏感词后再发布");
            addActionMessage("您发布的帖子中有敏感词汇，如下" + sb + "请删除这些敏感词后再发布");
            request.setAttribute("boardId", boardId);
            String sensitiveId = StringUtil.getUUID();
            Sensitive sensitive = new Sensitive(mainpost.getUserId(), sb.toString(), new Date(), sensitiveId, boardId);
            adminService.addSensitive(sensitive);
            return "success";
        }

    }

    public String deletePost() {
        HttpServletRequest request = ServletActionContext.getRequest();
        String postId = request.getParameter("postId");
        Mainpost mainpost = mainPostService.getMainPostsByPostId(postId);
        Forumstst forumstst = mainPostService.getForumststByUserId(postId);
        replyService.removeReplyByPostId(mainpost.getPostId());
        mainPostService.removeMainPost(mainpost);
        if (null != forumstst) {
            mainPostService.removeForumstst(forumstst);
        }
        boardId = mainpost.getBoardId();
        Board board = boardService.getBoardById(boardId);
        board.setPostNum(board.getPostNum() - 1);
        boardService.modifyBoardHits(board);
        request.setAttribute("boardId", boardId);
        return "success";
    }

    private void validatePost(Mainpost mainpost) {
        if (Validators.isEmpty(mainpost.getBoardId())) {
            addActionError("请选择你要发表的板块");
        }
        if (Validators.isEmpty(mainpost.getPostTitle())) {
            addActionError("请输入帖子标题");
        }
        if (Validators.isEmpty(mainpost.getUserId())) {
            addActionError("请登录后再发表帖子");
        }
        if (Validators.isEmpty(mainpost.getContent())) {
            addActionError("您没有输入任何内容");
        }

    }

    public BoardService getBoardService() {
        return boardService;
    }

    public void setBoardService(BoardService boardService) {
        this.boardService = boardService;
    }

    public MainPostService getMainPostService() {
        return mainPostService;
    }

    public void setMainPostService(MainPostService mainPostService) {
        this.mainPostService = mainPostService;
    }

    public ReplyService getReplyService() {
        return replyService;
    }

    public void setReplyService(ReplyService replyService) {
        this.replyService = replyService;
    }

    public ForumUserService getForumUserService() {
        return forumUserService;
    }

    public void setForumUserService(ForumUserService forumUserService) {
        this.forumUserService = forumUserService;
    }

    public AdminService getAdminService() {
        return adminService;
    }

    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

}
